<template>
  <div>
    <h1>团队管理页面</h1>
    <el-card class="box-card">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="请输入团队名称"
          clearable
          class="search-input"
        />
        <el-button type="primary" @click="fetchTeams">搜索</el-button>
      </div>

      <!-- 数据表格 -->
      <el-table
        :data="teams"
        border
        style="width: 100%"
        v-loading="loading"
        row-key="id"
      >
        <!-- 普通列 -->
        <el-table-column prop="id" label="团队ID" width="80" />
        <el-table-column prop="teamname" label="团队名称" />
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button type="primary" size="small" @click.stop="openEditDialog(scope.row)">
              修改
            </el-button>
            <el-button type="danger" size="small" @click.stop="handleDelete(scope.row)">
              删除
            </el-button>
            <el-button type="success" size="small" @click.stop="manageMembers(scope.row)">
              成员管理
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 修改团队弹窗 -->
    <el-dialog v-model="editDialogVisible" title="修改团队">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="团队名称">
          <el-input v-model="editForm.teamname" placeholder="请输入团队名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </div>
    </el-dialog>

    <!-- 成员管理弹窗 -->
    <el-dialog v-model="memberDialogVisible" title="成员管理" width="800px">
      <el-table
        :data="teamMembers"
        border
        style="width: 100%"
        v-loading="loadingMembers"
        @selection-change="handleMemberSelection"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="rolename" label="角色" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="电话" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="memberDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="openAddMemberDialog">新增成员</el-button>
        <el-button type="danger" @click="removeMembers">删除成员</el-button>
      </div>
    </el-dialog>

    <!-- 新增成员弹窗 -->
    <el-dialog v-model="addMemberDialogVisible" title="新增成员" width="800px">
      <div class="search-bar">
        <el-input
          v-model="userSearchQuery"
          placeholder="请输入用户名"
          clearable
          class="search-input"
        />
        <el-button type="primary" @click="fetchUsers">搜索</el-button>
      </div>
      <el-table
        :data="users"
        border
        style="width: 100%"
        v-loading="loadingUsers"
        @selection-change="handleUserSelection"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="rolename" label="角色" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="电话" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addMemberDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addMembers">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

// 状态
const teams = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const loading = ref(false);
const searchQuery = ref('');

// 成员管理弹窗状态
const memberDialogVisible = ref(false);
const teamMembers = ref([]);
const loadingMembers = ref(false);
const selectedMembers = ref([]);
const currentTeamId = ref(null);

// 新增成员弹窗状态
const addMemberDialogVisible = ref(false);
const users = ref([]);
const loadingUsers = ref(false);
const userSearchQuery = ref('');
const selectedUsers = ref([]);

// 修改团队弹窗状态
const editDialogVisible = ref(false);
const editForm = reactive({
  id: null,
  teamname: '',
});

// 获取团队列表
const fetchTeams = async () => {
  loading.value = true;
  try {
    const token = localStorage.getItem('token');
    if (!token) throw new Error('未找到 token，请重新登录');

    const response = await axios.get('http://localhost:8080/team/page', {
      params: {
        current: currentPage.value,
        size: pageSize.value,
        teamname: searchQuery.value || undefined,
      },
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });

    const { records, total: totalRecords } = response.data.data;
    teams.value = records;
    total.value = totalRecords;
  } catch (error) {
    ElMessage.error('获取团队数据失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 打开成员管理弹窗
const manageMembers = async (team) => {
  currentTeamId.value = team.id;
  memberDialogVisible.value = true;
  await fetchTeamMembers();
};

// 获取团队成员
const fetchTeamMembers = async () => {
  loadingMembers.value = true;
  try {
    const token = localStorage.getItem('token');
    if (!token) throw new Error('未找到 token，请重新登录');

    const response = await axios.get(`http://localhost:8080/team/${currentTeamId.value}/members`, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });

    teamMembers.value = response.data.data;
  } catch (error) {
    ElMessage.error('获取团队成员失败，请稍后重试');
  } finally {
    loadingMembers.value = false;
  }
};

// 删除成员
const removeMembers = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) throw new Error('未找到 token，请重新登录');

    await axios.put(
      'http://localhost:8080/user/batch-update-team',
      {
        teamId: null,
        userIds: selectedMembers.value,
      },
      {
        headers: {
          Authorization: `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
      }
    );

    ElMessage.success('成员删除成功');
    await fetchTeamMembers();
  } catch (error) {
    ElMessage.error('删除成员失败，请稍后重试');
  }
};

// 打开新增成员弹窗
const openAddMemberDialog = () => {
  addMemberDialogVisible.value = true;
  fetchUsers();
};

// 获取用户列表
const fetchUsers = async () => {
  loadingUsers.value = true;
  try {
    const token = localStorage.getItem('token');
    if (!token) throw new Error('未找到 token，请重新登录');

    const response = await axios.get('http://localhost:8080/user/page', {
      params: {
        current: 1,
        size: 10,
        username: userSearchQuery.value || undefined,
      },
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });

    users.value = response.data.data.records;
  } catch (error) {
    ElMessage.error('获取用户列表失败，请稍后重试');
  } finally {
    loadingUsers.value = false;
  }
};

// 新增成员
const addMembers = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) throw new Error('未找到 token，请重新登录');

    await axios.put(
      'http://localhost:8080/user/batch-update-team',
      {
        teamId: currentTeamId.value,
        userIds: selectedUsers.value,
      },
      {
        headers: {
          Authorization: `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
      }
    );

    ElMessage.success('成员新增成功');
    addMemberDialogVisible.value = false;
    await fetchTeamMembers();
  } catch (error) {
    ElMessage.error('新增成员失败，请稍后重试');
  }
};

// 处理成员选择
const handleMemberSelection = (selection) => {
  selectedMembers.value = selection.map((member) => member.id);
};

// 处理用户选择
const handleUserSelection = (selection) => {
  selectedUsers.value = selection.map((user) => user.id);
};

// 删除团队
const handleDelete = async (team) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) throw new Error('未找到 token，请重新登录');

    await ElMessageBox.confirm(
      `确定要删除团队 "${team.teamname}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    await axios.delete(`http://localhost:8080/team/${team.id}`, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });

    ElMessage.success('团队删除成功');
    fetchTeams();
  } catch (error) {
    ElMessage.error('删除团队失败，请稍后重试');
  }
};

// 打开修改团队弹窗
const openEditDialog = (team) => {
  editForm.id = team.id;
  editForm.teamname = team.teamname;
  editDialogVisible.value = true;
};

// 提交修改团队
const submitEdit = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) throw new Error('未找到 token，请重新登录');

    await axios.put(
      'http://localhost:8080/team/update',
      editForm,
      {
        headers: {
          Authorization: `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
      }
    );

    ElMessage.success('团队修改成功');
    editDialogVisible.value = false;
    fetchTeams();
  } catch (error) {
    ElMessage.error('修改团队失败，请稍后重试');
  }
};

// 分页切换
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchTeams();
};

// 页面加载时获取数据
fetchTeams();
</script>

<style scoped>
.box-card {
  margin: 20px;
  padding: 20px;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>